﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AvansRS.Domain;
using AvansRS.Domain.DataInterface;
using System.Net.Mail;
using System.Text;
using StructureMap;

namespace AvansRS.Web.Util
{
    public class ResetPassword
    {
        IAccountRepository _repository;

        public ResetPassword()
        {
            _repository = ObjectFactory.GetInstance<IAccountRepository>();
        }

        public void Reset(Account account)
        {
            account.GenerateResetKey();
            _repository.Save(account);

            SendMail(account);
        }

        public static string GetURLRootApplicationPath()
        {
            return (HttpContext.Current.Request.Url.AbsoluteUri.Replace(HttpContext.Current.Request.Url.PathAndQuery, string.Empty) +
            HttpContext.Current.Request.ApplicationPath);
        }


        private void SendMail(Account account)
        {            
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<html><body><b>Wachtwoord resetten</b>");
            sb.AppendLine("<p>Je krijgt deze email omdat jeje wachtwoord wilt resetten. Klik op deze");
            sb.AppendLine("<a href=\"" + GetURLRootApplicationPath() + "Account/ResetPassword?guid=" + account.ResetKey + "\">link</a> om je wachtwoord te resetten</p>");
            sb.AppendLine("</body></html>");

            MailMessage message = new MailMessage("avans@cravu.nl", account.Email);

            message.Subject = "Link om wachtwoord te resetten.";
            message.Body = sb.ToString();

            message.Headers.Add("MIME-Version", "1.0");
            message.Headers.Add("Content-type", "text/html; charset=iso-8859-1");
            message.IsBodyHtml = true;

            var client = new SmtpClient("smtp.upcmail.nl");
            client.Send(message);
        }
    }
}
